package dbtool

/*
 * @Author: huangchangqing
 * @Description: 构建mysql数据库连接
 */

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"database/sql"
	gormlogger "gorm.io/gorm/logger"
	"local.public/innerpkg/logger"

	"time"
)

// var dbBase *gorm.DB
var dbBusiness *gorm.DB
var dbWorkerOrder *gorm.DB
var dbLogs *gorm.DB

//func InitBaseDB(dsn string) error {
//	//dsn := "root:root@tcp(10.10.30.60:3306)/goechoexample?charset=utf8mb4&parseTime=True&loc=Local"
//	ldb, err := NewDB(dsn)
//	if err != nil {
//		return err
//	}
//	dbBase = ldb
//	logger.Debug("connect db successfully")
//	return nil
//}
//
//func CloseBaseDB() error {
//	sqlDB, err := dbBase.DB()
//	if err != nil {
//		return err
//	}
//	return sqlDB.Close()
//}

func InitBusinessDB(dsn string) error {
	//dsn := "root:root@tcp(10.10.30.60:3306)/goechoexample?charset=utf8mb4&parseTime=True&loc=Local"
	ldb, err := NewDB(dsn)
	if err != nil {
		return err
	}
	dbBusiness = ldb
	//logger.Debug("connect business db successfully")
	return nil
}

func CloseBusinessDB() error {
	sqlDB, err := dbBusiness.DB()
	if err != nil {
		return err
	}
	return sqlDB.Close()
}

func InitWorkerOrderDB(dsn string) error {
	ldb, err := NewDB(dsn)
	if err != nil {
		return err
	}
	dbWorkerOrder = ldb
	//logger.Debug("connect worker order db successfully")
	return nil
}

func CloseWorkerOrderDB() error {
	sqlDB, err := dbWorkerOrder.DB()
	if err != nil {
		return err
	}
	return sqlDB.Close()
}

func InitLogsDB(dsn string) error {
	ldb, err := NewDB(dsn)
	if err != nil {
		return err
	}
	dbLogs = ldb
	//logger.Debug("connect logs db successfully")
	return nil
}

func CloseLogsDB() error {
	sqlDB, err := dbLogs.DB()
	if err != nil {
		return err
	}
	return sqlDB.Close()
}

// NewDB 新建DB连接
func NewDB(dsn string) (*gorm.DB, error) {
	// 打印数据库连接串
	//logger.Debug("打开连接（MySQL）：", dsn)

	// 打开数据库链接
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: gormlogger.Default.LogMode(gormlogger.Info),
		//NamingStrategy: schema.NamingStrategy{
		//	TablePrefix:   pubdata, // 表前缀
		//	SingularTable: true,   // 禁用表名复数
		//},
		DisableForeignKeyConstraintWhenMigrating: true, // 禁用外键
		QueryFields:                              true, // 解决查询全部字段可能不走索引的问题
	})
	// 错误退出
	if err != nil {
		message := fmt.Sprintf("数据库连接异常：%s", err.Error())
		logger.Error(message)
		panic(message)
	}

	// 设置数据库连接池
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(10)                                 // 空闲连接池中连接的最大数量
	sqlDB.SetMaxOpenConns(100)                                // 最大连接数量
	sqlDB.SetConnMaxIdleTime(time.Minute * time.Duration(60)) // 连接最大可复用时间
	logger.Debug("数据库连接已经建立:", dsn)
	// 获取数据库连接
	return db, nil
}

//// GetBaseDB 获取DBhandle
//func GetBaseDB() *gorm.DB {
//	if dbBase == nil {
//		panic("db is nil")
//	}
//	return dbBase
//}

// GetBusinessDB 获取DBhandle
func GetBusinessDB() *gorm.DB {
	if dbBusiness == nil {
		panic("db is nil")
	}
	return dbBusiness
}
// GetBusinessDB 获取DBhandle
func GetWorkerOrderDB() *gorm.DB {
	if dbWorkerOrder == nil {
		panic("db is nil")
	}
	return dbWorkerOrder
}

// GetLogsDB 获取DBhandle
func GetLogsDB() *gorm.DB {
	if dbLogs == nil {
		panic("db is nil")
	}
	return dbLogs
}


func GetDB(dbAlias string) *gorm.DB {
	if dbAlias == "" || dbAlias == "business"  {
		if dbBusiness == nil {
			panic("db is nil")
		}
		return dbBusiness
	}
	if dbAlias == "worker_order" || dbAlias == "workerorder"  {
		if dbWorkerOrder == nil {
			panic("db is nil")
		}
		return dbWorkerOrder
	}
	if dbAlias == "logs"  {
		if dbBusiness == nil {
			panic("db is nil")
		}
		return dbBusiness
	}
	return nil
}

func InitDB(dbAlias string,dsn string) error {
	ldb, err := NewDB(dsn)
	if err != nil {
		return err
	}
	if dbAlias == "" || dbAlias == "business"  {
		dbBusiness = ldb
	} else if dbAlias == "worker_order" || dbAlias == "workerorder"  {
		dbWorkerOrder = ldb
	} else if dbAlias == "logs"  {
		dbLogs = ldb
	} else {
		logger.Debug("dbAlias 不正确")
		return nil
	}
	return nil
}


func CloseDB(dbAlias string) error {
	var sqlDB *sql.DB
	var err error
	if dbAlias == "" || dbAlias == "business"  {
		sqlDB, err = dbBusiness.DB()
	} else if dbAlias == "worker_order" || dbAlias == "workerorder"  {
		sqlDB, err = dbWorkerOrder.DB()
	} else if dbAlias == "logs"  {
		sqlDB, err = dbLogs.DB()
	} else {
		logger.Debug("dbAlias 不正确")
		return nil
	}
	if err != nil {
		return err
	}
	return sqlDB.Close()
}